<template>
  <div class="w-full p-6 flex h-full justify-center items-center bg-bg">
    <el-scrollbar height="100%" class="w-full h-full rounded-lg">
      <div class="w-full mb-4 flex justify-center">
        <el-date-picker
          v-model="date"
          type="monthrange"
          range-separator="至"
          start-placeholder="开始月份"
          end-placeholder="结束月份"
          @change="dateChange"
          @blur="dateBlur"
        >
        </el-date-picker>
      </div>
      <div class="w-full flex flex-col md:flex-row h-128">
        <div
          class="w-full md:w-1/2 md:mr-6 bg-white h-full rounded-lg"
          id="nameChart"
        ></div>
        <div
          class="w-full mt-4 md:mt-0 md:w-1/2 bg-white h-full rounded-lg"
          id="typeChart"
        ></div>
      </div>
      <div class="flex flex-row justify-between my-4">
        <el-input
          v-model="search"
          placeholder="根据名称进行搜索"
          prefix-icon="el-icon-search"
          @change="searchChange"
        ></el-input>
      </div>
      <vxe-table
        align="center"
        :data="listData"
        :loading="loading"
        round
        border
      >
        <vxe-column type="seq" width="60"></vxe-column>
        <vxe-column field="staffId" :visible="false"> </vxe-column>
        <vxe-column field="name" title="名称"></vxe-column>
        <vxe-column field="staffNumber" title="学号"></vxe-column>
        <vxe-column field="num" title="成果数量"></vxe-column>
        <vxe-column title="操作" width="100" show-overflow>
          <template #default="{ row }">
            <vxe-button
              type="text"
              icon="fa fa-search"
              @click="searchEvent(row)"
            ></vxe-button>
          </template>
        </vxe-column>
      </vxe-table>
      <div class="flex flex-row justify-between mt-4">
        <el-button :disabled="!pageInfo.hasPre" @click="prePage"
          >上一页</el-button
        >
        <p>{{ pageInfo.current }}</p>
        <el-button :disabled="!pageInfo.hasNext" @click="nextPage"
          >下一页</el-button
        >
      </div>
    </el-scrollbar>
  </div>
  <el-dialog
    title="人员成果详情"
    v-model="showDialog"
    destroy-on-close
    fullscreen
    append-to-body
  >
    <re-staff-award-list></re-staff-award-list>
  </el-dialog>
</template>

<script lang="ts">
import { tryOnUnmounted, useEventListener, useTimeoutFn } from "@vueuse/core";
import { nextTick, onMounted, reactive, ref } from "vue";
import {
  analysisByName,
  analysisByNameLimitByDate,
  analysisGroupByStaffNameLimitByDate,
  AwardAnalysisNameDTO,
  AwardAnalysisNamePageDTO,
  AwardAnalysisTypeDTO,
  getAnalysis
} from "/@/api/award";
import echarts from "/@/plugins/echarts";
import { errorMessage } from "/@/utils/message";
import { useAwardStoreHook } from "/@/store/modules/award";
import ReStaffAwardList from "/@/components/ReStaffAwardList/index.vue";
let nameChart: any = null;
let typeChart: any = null;
export default {
  components: {
    ReStaffAwardList
  },
  setup() {
    const loading = ref(true);
    const search = ref("");
    const date = ref<Date[]>([]);
    const pageInfo = reactive({
      hasNext: false,
      hasPre: false,
      current: 1,
      size: 10
    });
    const listData = ref<AwardAnalysisNameDTO[]>([]);
    const searchPage = async () => {
      let res = null;
      if (date.value.length === 0) {
        res = await analysisByName(
          search.value,
          pageInfo.current,
          pageInfo.size
        );
      } else {
        res = await analysisByNameLimitByDate(
          search.value,
          pageInfo.current,
          pageInfo.size,
          date.value[0],
          date.value[1]
        );
      }
      if (res.code === 1) {
        const data = res.response as AwardAnalysisNamePageDTO;
        pageInfo.hasNext = data.hasNext;
        pageInfo.hasPre = data.hasPre;
        listData.value = data.list;
      }
    };
    const searchChange = async () => {
      pageInfo.current = 1;
      if (search.value !== "") {
        searchPage();
      } else {
        getListData();
      }
    };

    const showDialog = ref(false);
    const awardStore = useAwardStoreHook();
    const searchEvent = async (row: any) => {
      const staffId = row["staffId"];
      awardStore.setStaffId(staffId);
      showDialog.value = true;
    };
    const prePage = () => {
      if (pageInfo.hasPre) {
        pageInfo.current--;
        if (search.value === "") {
          getListData();
        } else {
          searchPage();
        }
      }
    };
    const nextPage = () => {
      if (pageInfo.hasNext) {
        pageInfo.current++;
        if (search.value === "") {
          getListData();
        } else {
          searchPage();
        }
      }
    };

    const awardAnalysisByName = ref<AwardAnalysisNameDTO[]>([]);
    const awardAnalysisByType = ref<AwardAnalysisTypeDTO[]>([]);
    const getAnalysisByName = async () => {
      const res = await getAnalysis("name");
      if (res.code === 1) {
        const data = res.response as AwardAnalysisNameDTO[];
        awardAnalysisByName.value = data;
        loading.value = false;
        getListData();
      } else {
        errorMessage(res.message);
      }
    };
    const getAnalysisByType = async () => {
      const res = await getAnalysis("type");
      if (res.code === 1) {
        const data = res.response as AwardAnalysisTypeDTO[];
        awardAnalysisByType.value = data;
      } else {
        errorMessage(res.message);
      }
    };

    const getListData = () => {
      const start = (pageInfo.current - 1) * 10;
      let end = pageInfo.current * 10 - 1;
      if (end >= awardAnalysisByName.value.length) {
        end = awardAnalysisByName.value.length - 1;
        pageInfo.hasNext = false;
      } else {
        pageInfo.hasNext = true;
      }
      if (start !== 0) {
        pageInfo.hasPre = true;
      } else {
        pageInfo.hasPre = false;
      }
      listData.value = [];
      for (let i = start; i <= end; i++) {
        listData.value.push(awardAnalysisByName.value[i]);
      }
    };

    const initNameChart = async () => {
      await getAnalysisByName();
      flushNameChart();
    };
    const flushNameChart = () => {
      const chart = document.getElementById("nameChart");
      if (!chart) return;
      nameChart = echarts.init(chart);
      nameChart.clear();
      const legendData = [];
      const seriesDate = [];
      awardAnalysisByName.value.forEach(item => {
        legendData.push(item.name);
        seriesDate.push({ name: item.name, value: item.num });
      });
      nameChart.setOption({
        title: {
          text: "按人名统计",
          top: "20",
          left: "center"
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
          type: "scroll",
          orient: "vertical",
          right: 0,
          top: 20,
          bottom: 20,
          data: legendData
        },
        series: [
          {
            name: "姓名",
            type: "pie",
            radius: "55%",
            center: ["40%", "50%"],
            data: seriesDate,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)"
              }
            }
          }
        ]
      });
    };

    const initTypeChart = async () => {
      await getAnalysisByType();
      flushTypeChart();
    };
    const flushTypeChart = () => {
      const chart = document.getElementById("typeChart");
      if (!chart) return;
      typeChart = echarts.init(chart);
      typeChart.clear();
      const legendData = [];
      const seriesDate = [];
      awardAnalysisByType.value.forEach(item => {
        legendData.push(item.type);
        seriesDate.push({ name: item.type, value: item.num });
      });
      typeChart.setOption({
        title: {
          text: "按类型统计",
          top: "20",
          left: "center"
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
          type: "scroll",
          orient: "vertical",
          right: 0,
          top: 20,
          bottom: 20,
          data: legendData
        },
        series: [
          {
            name: "姓名",
            type: "pie",
            radius: "55%",
            center: ["40%", "50%"],
            data: seriesDate,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)"
              }
            }
          }
        ]
      });
    };

    const dateChange = async () => {
      awardStore.setStartTime(date.value[0]);
      awardStore.setEndTime(date.value[1]);
      const res1 = await analysisGroupByStaffNameLimitByDate(
        "name",
        date.value[0],
        date.value[1]
      );
      if (res1.code === 1) {
        awardAnalysisByName.value = res1.response;
        flushNameChart();
        getListData();
      }
      const res2 = await analysisGroupByStaffNameLimitByDate(
        "type",
        date.value[0],
        date.value[1]
      );
      if (res2.code === 1) {
        awardAnalysisByType.value = res2.response;
        flushTypeChart();
      }
    };

    const dateBlur = async () => {
      if (date.value === null || date.value.length === 0) {
        awardStore.setStartTime(null);
        awardStore.setEndTime(null);
        initNameChart();
        initTypeChart();
      }
    };

    onMounted(() => {
      initNameChart();
      initTypeChart();
      nextTick(() => {
        useEventListener("resize", () => {
          if (!nameChart) return;
          useTimeoutFn(() => {
            nameChart.resize();
          }, 180);
        });
        useEventListener("resize", () => {
          if (!typeChart) return;
          useTimeoutFn(() => {
            typeChart.resize();
          }, 180);
        });
      });
    });

    tryOnUnmounted(() => {
      if (nameChart) {
        nameChart.dispose();
        nameChart = null;
      }
      if (typeChart) {
        typeChart.dispose();
        typeChart = null;
      }
    });

    return {
      awardAnalysisByName,
      awardAnalysisByType,
      loading,
      search,
      listData,
      searchChange,
      searchEvent,
      prePage,
      nextPage,
      dateChange,
      dateBlur,
      pageInfo,
      date,
      showDialog
    };
  }
};
</script>

<style scoped></style>
